package com.huazi.www.user.wwwChaCtLuo.util;

import java.sql.*;

public class BaseDao {
    public Connection conn = null;                //数据库连接对象
    public PreparedStatement psmt = null;       //处理命令
    public ResultSet rs = null;                 //查询语句

    //打开数据库
    public Connection gerConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hospital?useUnicode=true&characterEncoding=utf8", "root", "123456");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    //关闭所有资源
    public void closeAll(Connection conn, PreparedStatement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //3、增、删、改通用方法
    public int executeUpdate(String sql, Object... param) {
        int num = 0;//影响行数
        conn = gerConnection();
        try {
            psmt = conn.prepareStatement(sql);
            //为参数赋值
            if (param != null) {
                for (int i = 0; i < param.length; i++) {
                    psmt.setObject(i + 1, param[i]);
                }
            }
            //执行sql语句
            num = psmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeAll(conn, psmt, null);
        }
        return num;
    }

    /**
     * 查询的通用方法
     *
     * @param sql
     * @param param
     * @return
     */
    public ResultSet excuteQuery(String sql, Object... param) {
        conn = gerConnection();
        try {
            psmt = conn.prepareStatement(sql);
            for (int i = 0; i < param.length; i++) {
                psmt.setObject(i + 1, param[i]);
            }
            rs = psmt.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rs;
    }
}
